package zb.blog.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zb.blog.base.bean.Result;
import zb.blog.base.cache.DataToCache;
import zb.blog.base.global.GlobalVar;
import zb.blog.base.util.EncryptUtil;
import zb.blog.base.util.StringUtil;
import zb.blog.bean.PraiseArticleBean;
import zb.blog.dao.PraiseDao;
import zb.blog.service.IPraiseService;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.List;

@Service
public class PraiseService implements IPraiseService {
    @Autowired
    private PraiseDao praiseDao;


    @Override
    public Result addPraise(String artId, Integer praiseId, Integer type, HttpServletRequest request) {
        Result r = new Result();
        if (type != null && type == 2) {
            artId = GlobalVar.MESSAGE_ID;//设置默认的留言ID
        }
        if (artId == null || praiseId == null) {
            r.setMsg("参数错误");
            r.setSuccess(GlobalVar.FAIL);
            return r;
        }
        String ip = StringUtil.getIpAddr(request);
        int id = EncryptUtil.customDecrypt(artId);
        if (!DataToCache.getArticleIsClickPraise(String.valueOf(id), ip)) {
            if (id == 2) {
                r.setMsg("您今天已经赞过博主了，明天再来吧！");
            } else {
                r.setMsg("这篇文章您今天已经赞过了，明天再来吧！");
            }
            r.setSuccess(GlobalVar.FAIL);
            return r;
        }
        try {
            int count = praiseDao.updatePraise(id, praiseId);
            if (count == 1) {
                r.setSuccess(GlobalVar.SUCCESS);
                r.setMsg("点赞成功！");
                //设置ip到缓存
                DataToCache.setIpToArtId(String.valueOf(id), ip);
            } else {
                r.setSuccess(GlobalVar.FAIL);
                r.setMsg("点赞成功！");
            }
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("点赞失败！");
            return r;
        }
    }

    @Override
    public Result getPraiseByArtId(String artId, Integer type) {
        Result r = new Result();
        if (type != null && type == 2) {
            artId = GlobalVar.MESSAGE_ID;//设置默认的留言ID
        }
        if (artId == null) {
            r.setMsg("参数错误，加载点赞失败！");
            r.setSuccess(GlobalVar.FAIL);
            return r;
        }
        List<PraiseArticleBean> praiseList = praiseDao.getPraiseByArtId(EncryptUtil.customDecrypt(artId));
        if (praiseList != null && praiseList.size() == 5) {
            r.setSuccess(GlobalVar.SUCCESS);
            r.setMsg("加载点赞成功！");
            r.setData(praiseList);
        } else {
            r.setSuccess(GlobalVar.SUCCESS);
            r.setMsg("加载点赞失败！");
        }
        return r;
    }
}
